package com.runa.monitor.platinterface.meter3_0.session;

import com.runa.persistence.util.SpringContextUtil;
import com.runa.monitor.platinterface.meter3_0.handle.AbsMsgHandler;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;

/**
 * @author diandian
 * @Date 2022/11/18 20:11
 */
@Slf4j
public class WebSocketClient extends Endpoint {

    private String identity;

    private AbsMsgHandler messageHandler;

    private SessionManager sessionManager;

    public WebSocketClient(String identity, AbsMsgHandler messageHandler) {
        this.identity = identity;
        this.messageHandler = messageHandler;
        this.sessionManager = SpringContextUtil.getBean(SessionManager.class);
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        MessageHandler messageHandler = this.messageHandler.getMessageHandler(session, config,identity);
        session.addMessageHandler(messageHandler);
    }

    public void onClose(Session session, CloseReason closeReason) {
        try {
            log.info("琅卡博3.0onClose");
            sessionManager.notifyEndHandleMsg(identity);
        } catch (Exception e) {

        } finally {
            WebSocketPool.removeSession(identity);
        }
    }

    public void onError(Session session, Throwable throwable) {
        try {
            log.info("琅卡博3.0onError");
            sessionManager.notifyEndHandleMsg(identity);
        } catch (Exception e) {

        } finally {
            WebSocketPool.removeSession(identity);
        }
    }
}
